package com.stone.util;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

public class DateUtils {
	
	/**
	 * @param format
	 * @param date
	 * @param month 0:当前自然月,1:上个自然月
	 * @return
	 * @throws ParseException
	 */
    public static String[] getNLastMonth(String format,Date date,int month){
    	SimpleDateFormat sdf = new SimpleDateFormat(format);
    	Calendar c1 = Calendar.getInstance();
		c1.setTime(date);
		c1.add(Calendar.MONTH, -month);
		c1.set(Calendar.DAY_OF_MONTH, 1);
    	
		Calendar c2 = Calendar.getInstance();
		c2.setTime(date);
		c2.add(Calendar.MONTH, -month+1);
		c2.set(Calendar.DAY_OF_MONTH, 0);
		
		String monthStart = sdf.format(c1.getTime());
		String monthEnd = sdf.format(c2.getTime());
		
		return new String[]{monthStart,monthEnd};
    }
	
	/**
	 * @param format
	 * @param date
	 * @param year 0:当年，1：上个自然年
	 * @return
	 */
	public static String[] getNLastYear(String format,Date date,int year) {
		SimpleDateFormat sdf = new SimpleDateFormat(format);
		Calendar c1 = Calendar.getInstance();
		c1.setTime(date);
		c1.clear(Calendar.MONTH);
		c1.add(Calendar.YEAR, -year);
		c1.set(Calendar.DAY_OF_MONTH, 1);

		Calendar c2 = Calendar.getInstance();
		c2.setTime(date);
		c2.clear(Calendar.MONTH);
		c2.add(Calendar.YEAR, -year);
		c2.set(Calendar.MONTH, 11);
		c2.set(Calendar.DAY_OF_MONTH, c2.getActualMaximum(Calendar.DAY_OF_MONTH));

		String yearStart = sdf.format(c1.getTime());
		String yearkEnd = sdf.format(c2.getTime());

		return new String[]{yearStart,yearkEnd};
	}
	
	/**
	 * @param format
	 * @param date
	 * @param week 0:本周,1:上周
	 * @return
	 */
	public static String[] getNLastWeek(String format, Date date, int week) {
		SimpleDateFormat sdf = new SimpleDateFormat(format);
		Calendar c1 = Calendar.getInstance();
		c1.setTime(date);

		Calendar c2 = Calendar.getInstance();
		c2.setTime(date);

		int dayOfWeek = c1.get(Calendar.DAY_OF_WEEK) - 1;
		int offset1 = 1 - dayOfWeek;
		int offset2 = 7 - dayOfWeek;

		c1.add(Calendar.DATE, offset1 - 7 * week);
		c2.add(Calendar.DATE, offset2 - 7 * week);

		String weekStart = sdf.format(c1.getTime());
		String weekEnd = sdf.format(c2.getTime());

		return new String[]{weekStart,weekEnd};
	}
	
	public static String getDelayHour(int delay, String format,Date date) throws ParseException {
		Calendar calendar = Calendar.getInstance();
		calendar.setTime(date);
		calendar.add(Calendar.HOUR, -delay);
		return new SimpleDateFormat(format).format(calendar.getTime());
	}
	
	public static String getDelayDay(int delay,String format,Date date) throws ParseException{
		Calendar calendar = Calendar.getInstance();
		calendar.setTime(date);
		calendar.add(Calendar.DATE,-delay); 
		return new SimpleDateFormat(format).format(calendar.getTime());
	}
}
